<script setup lang="ts">
import { ref } from 'vue'
import Request from '@/api/axios'
import { HttpStatusCode } from 'axios'
import { message } from 'ant-design-vue'
const passwordForm = ref({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})


const validateConfirmPassword = (rule, value) => {
    if (value !== passwordForm.value.newPassword) {
        return Promise.reject('两次输入的密码不一致')
    }
    return Promise.resolve()
}

const handlePasswordChange = async () => {
    try {
        const response = await Request.post({
            url: `/user/changePassword`,
            data: {
                oldPassword: passwordForm.value.oldPassword,
                newPassword: passwordForm.value.newPassword
            }
        })
        if (response.code === HttpStatusCode.Ok) {
            message.success('密码修改成功')
            passwordForm.value = {
                oldPassword: '',
                newPassword: '',
                confirmPassword: ''
            }
        } else {
            message.error('密码修改失败')
            console.log(response.msg)
        }
    } catch (err) {
        message.error('网络错误，请稍后重试')
        console.log(err)
    }
}
</script>
<template>
    <a-card title="密码保护" bordered>
        <a-form :model="passwordForm" @finish="handlePasswordChange" :label-col="{ span: 2 }">
            <a-form-item label="旧密码" name="oldPassword" rules="[{ required: true, message: '请输入旧密码' }]">
                <a-input-password v-model:value="passwordForm.oldPassword" />
            </a-form-item>
            <a-form-item label="新密码" name="newPassword"
                rules="[{ required: true, message: '请输入新密码' }, { min: 6, message: '密码长度不能少于6位' }]">
                <a-input-password v-model:value="passwordForm.newPassword" />
            </a-form-item>
            <a-form-item label="确认密码" name="confirmPassword"
                rules="[{ required: true, message: '请确认新密码' }, { validator: validateConfirmPassword }]">
                <a-input-password :visibility-toggle="false" v-model:value="passwordForm.confirmPassword" />
            </a-form-item>
            <a-form-item>
                <a-button type="primary" html-type="submit">修改密码</a-button>
            </a-form-item>
        </a-form>
    </a-card>
</template>